<?php

namespace app\common\model\vod;

use helper\Tree;
use tencentcloud\Vod;

class CateModel
{
  private $vodModel;

  //初始化
  public function __construct()
  {
    $this->vodModel = new Vod();
  }

  /**
   * 同步视频分类
   * @return array|mixed
   * @throws \Exception
   */
  public function refresh()
  {
    $cate     = $this->vodModel->execFun('DescribeAllClass', []);
    $cateList = [];
    foreach ($cate['ClassInfoSet'] as $k => $v) {
      if($v['ClassId']==0) continue; //排除掉其他分类
      $item       = [
          'id' => $v['ClassId'],
          'pid' => $v['ParentId'] == -1 ? 0 : $v['ParentId'],
          'name' => $v['ClassName'],
          'level' => $v['Level']
      ];
      $cateList[] = $item;
    }
    cache('vod_cate', $cateList);
    return $cateList;
  }

  /**
   * 获取视频分类
   * @return mixed
   * @throws \Exception
   */
  public function getList()
  {
    $cate = empty(cache('vod_cate')) ? $this->refresh() : cache('vod_cate');
    return Tree::tree($cate, 'name');
  }

  /**
   * 添加分类
   * @param $pid
   * @param $name
   * @return bool
   * @throws \Exception
   */
  public function add($pid, $name)
  {
    $this->vodModel->execFun('CreateClass', [
        'ParentId' => $pid,
        'ClassName' => $name,
    ]);
    $this->refresh();
    return true;
  }

  /**
   * 修改分类
   * @param $id
   * @param $name
   * @return bool
   * @throws \Exception
   */
  public function edit($id, $name)
  {
    $this->vodModel->execFun('ModifyClass', [
        'ClassId' => (int)$id,
        'ClassName' => $name
    ]);
    $this->refresh();
    return true;
  }

  /**
   * 删除分类
   * @param $id
   * @return bool
   * @throws \Exception
   */
  public function del($id)
  {
    $this->vodModel->execFun('DeleteClass', [
        'ClassId' => (int)$id
    ]);
    $this->refresh();
    return true;
  }

}